package tt.dz.egobus.servicemanager.core.resovler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局统一异常处理机制
 */
public class ExceptionMappingExceptionResolver extends SimpleMappingExceptionResolver {


    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionMappingExceptionResolver.class);

    @Override
    protected ModelAndView getModelAndView(String viewName, Exception ex,
                                           HttpServletRequest request) {
        //将异常信息打印到日志中
        logger.error(" Exception Resovler -->:", ex);
        return super.getModelAndView(viewName, ex, request);
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
                                              Object handler, Exception ex) {
        // Expose ModelAndView for chosen error view.
        String viewName = determineViewName(ex, request);
        if (viewName != null) {
            // Apply HTTP status code for error views, if specified.
            // Only apply it if we're processing a top-level request.
            Integer statusCode = determineStatusCode(request, viewName);
            if (statusCode != null) {
                applyStatusCodeIfPossible(request, response, statusCode);
            }
            request.setAttribute("exceptionMessage", ex.getMessage());
            return getModelAndView(viewName, ex, request);
        } else {
            return null;
        }
    }

}
